package com.qingke.easyjava.hibernate.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.hibernate.query.Query;

import com.qingke.easyjava.hibernate.bean.Apartment;
import com.qingke.easyjava.hibernate.bean.College;
import com.qingke.easyjava.hibernate.bean.Student;

public class StudentDao {
	private	Session session;
	public StudentDao(Session session){
		this.session=session;
	}
	
	public List<Student> list(){
		Query<Student> query=session.createQuery(" from Student ", Student.class);
		return query.getResultList();
	}
	public List<Student> listByname(String name){
		Query<Student> query=session.createQuery(" from Student where firstname like:name or lastname like:name ", Student.class);
		query.setParameter("name","%"+ name+"%");
		
		return query.getResultList();
	}
	public List<Apartment> listApartment(){
		Query<Apartment> query=session.createQuery("from Apartment",Apartment.class);
		return query.getResultList();
	}
	public Student getStudentById(int id){
		return session.get(Student.class, id);
	}
	public List<College> listCollege(){
		Query<College> query =session.createQuery("from College",College.class);
		return query.getResultList();
	}
	public List<? extends Object> allList(Object obj){
		Query<? extends Object> query =session.createQuery("from "+obj.getClass().getName(),obj.getClass());
		return query.getResultList();
	}
	public Object getObjectById(Object obj , int id){
		return session.get(obj.getClass(), id);
	}
	
	public void insert(Object obj){
		Transaction tx=session.beginTransaction();
		try{
			session.save(obj);
			tx.commit();
			
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
		}
	}
	
	public void update(Object obj){
		Transaction tx=session.beginTransaction();
		try{
			session.update(obj);
			tx.commit();
			
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void delete(Object obj){
		Transaction tx=session.beginTransaction();
		try{
			session.delete(obj);
			tx.commit();
			
		}catch(HibernateException e){
			e.printStackTrace();
			tx.rollback();
		}
	}
	
}
